package com.liuyc.lib.ui.nestedScroll

import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.widget.LinearLayout
import androidx.annotation.AttrRes
import androidx.annotation.RequiresApi
import androidx.annotation.StyleRes
import androidx.recyclerview.widget.RecyclerView

abstract class ChildNestedScrollLinearLayout : LinearLayout {

    /**
     * 外部设置的
     */
    protected var mChildRecycleView: ChildNestedRecycleView? = null

    constructor(context: Context) : super(context) {}
    constructor(
        context: Context, attrs: AttributeSet?
    ) : super(context, attrs) {
    }

    constructor(
        context: Context, attrs: AttributeSet?,
        @AttrRes defStyleAttr: Int
    ) : super(context, attrs, defStyleAttr) {
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    constructor(
        context: Context, attrs: AttributeSet?,
        @AttrRes defStyleAttr: Int, @StyleRes defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {
    }

    /**
     * 重写此方法可以接管 滚动事件
     */
    fun receiverScrollByParent(dy: Int, consumed: IntArray) {
        mChildRecycleView?.let {

                if (dy > 0){
                    it.scrollBy(0, dy)
                    //将里面 recycle 滑动的距离回传给外面的 recycle
                    consumed[1] = dy
                    it.setScrollState(RecyclerView.SCROLL_STATE_DRAGGING)
                }else{
                    var childScrollY = it.computeVerticalScrollOffset()

                    if (childScrollY > Math.abs(dy)){
                        it.scrollBy(0, dy)
                        //将里面 recycle 滑动的距离回传给外面的 recycle
                        consumed[1] = dy
                        it.setScrollState(RecyclerView.SCROLL_STATE_DRAGGING)
                    }else{
                        // 子类处理掉自己最后能处理的，其余的交给父类处理
                        it.scrollBy(0, childScrollY)
                        consumed[1] = -childScrollY
                    }
                }

        }
    }


}